import { defHttp } from "/@/utils/http/axios"
import { LoginParams, LoginResultModel, GetUserInfoModel } from "./model/userModel"
import { encryptByBase64, AesEncryption } from "/@/utils/cipher-plus"
import { ErrorMessageMode } from "/#/axios"
import { useMessage } from "/@/hooks/web/useMessage"
import { useUserStoreWithOut } from "/@/store/modules/user"
import * as iamCache from "/@/utils/cache/module/iam"
import { TOKEN_KEY } from "/@/enums/cacheEnum"
import { router } from "/@/router"
import { PageEnum } from "/@/enums/pageEnum"
import qs from "qs"
import { RequestHeaderEnum } from "/@/enums/httpEnum"

import { Api } from "/@/api/url"
import { useGlobSetting } from "/@/hooks/setting"
const globSetting = useGlobSetting()

const { createErrorModal } = useMessage()

export const saveUserPermission = (params) =>
  defHttp.post({ url: "/system-service/user/assignPermission", params })

export const listPermission = (params) =>
  defHttp.get({ url: "/system-service/user/listPermission", params })


/**
 * 修改用户密码
 * @returns
 */
export const userResetPassword = (params, handleSuccess) => {
  return defHttp.post({ url: Api.userResetPassword, params }, { isTransformResponse: false }).then((res) => {
    handleSuccess(res)
  })
}

/**
 * 更新用户信息
 * @returns
 */
export const updateProfile = (params) => {
  return defHttp.post({ url: Api.updateProfile, params })
}


/**
 * @description: user phoneLogin api
 */
export function phoneLoginApi(params: LoginParams, mode: ErrorMessageMode = "modal") {
  return defHttp.post<LoginResultModel>(
    {
      url: Api.phoneLogin,
      params,
    },
    {
      errorMessageMode: mode,
    }
  )
}

/**
 * @description: getUserInfo
 */
export function getUserInfo() {
  return defHttp.get<GetUserInfoModel>({ url: "/iam-service/user/me/getInfo" }, { errorMessageMode: "message" }).catch((e) => {
    // 捕获接口超时异常,跳转到登录界面
    if (e && (e.message.includes("timeout") || e.message.includes("401"))) {
      //接口不通时跳转到登录界面
      const userStore = useUserStoreWithOut()
      userStore.setToken("")
      router.push(PageEnum.READY_SSO_LOGIN)
    }
  })
}

export function getUserBaseInfo() {
  return defHttp.get<any>({ url: Api.getUserBaseInfo }, { errorMessageMode: "message" }).catch((e) => {
    // 捕获接口超时异常,跳转到登录界面
    if (e && (e.message.includes("timeout") || e.message.includes("401"))) {
      //接口不通时跳转到登录界面
      const userStore = useUserStoreWithOut()
      userStore.setToken("")
      router.push(PageEnum.READY_SSO_LOGIN)
    }
  })
}

/**
 * @description: 注册接口
 */
export async function register(params) {
  const apiParams = { ...params }
  return defHttp.post({ url: Api.registerApi, params: apiParams }, { isReturnNativeResponse: true, errorMessageMode: "none" })
}

/**
 *校验用户是否存在
 * @param params
 */
export const checkOnlyUser = (params) => defHttp.get({ url: Api.checkOnlyUser, params }, { isTransformResponse: false })
/**
 *校验手机号码
 * @param params
 */
export const phoneVerify = (params) => defHttp.post({ url: Api.phoneVerify, params }, { isTransformResponse: false })
/**
 *密码修改
 * @param params
 */
export const passwordChange = (params) => defHttp.get({ url: Api.passwordChange, params }, { isTransformResponse: false })
/**
 * @description: 第三方登录
 */
export function thirdLogin(params, mode: ErrorMessageMode = "modal") {
  return defHttp.get<LoginResultModel>(
    {
      url: `${Api.thirdLogin}/${params.token}/${params.thirdType}`,
    },
    {
      errorMessageMode: mode,
    }
  )
}
/**
 * @description: 获取第三方短信验证码
 */
export function setThirdCaptcha(params) {
  return new Promise((resolve, reject) => {
    defHttp.post({ url: Api.getThirdCaptcha, params }, { isTransformResponse: false }).then((res) => {
      console.log(res)
      if (res.success) {
        resolve(true)
      } else {
        createErrorModal({ title: "错误提示", content: res.message || "未知问题" })
        reject()
      }
    })
  })
}

/**
 *
 * @returns 获取当前登录用户所属租户
 */
export async function listTenant(accessToken?: string) {
  const headers = accessToken ? { Authorization: "Bearer " + accessToken } : {}
  return defHttp.get({ url: '/iam-service/tenant/listMeTenant', params: {}, headers })
}

/**
 *
 * @returns 获取当前登录用户所属租户
 */
export async function listTenantTree(accessToken?: string) {
  const headers = accessToken ? { Authorization: "Bearer " + accessToken } : {}
  return defHttp.get({ url: Api.listTenantTree, params: {}, headers })
}

export async function selectLoginTenant(params) {
  const headers = {}
  headers[RequestHeaderEnum.TENANT_ID] = params.tenantId
  return defHttp.post({ url: '/iam-service/tenant/selectLoginTenant', params, headers })
}

export async function switchTenant(params) {
  const headers = {}
  headers[RequestHeaderEnum.TENANT_ID] = params.tenantId
  return defHttp.post({
    url: '/iam-service/tenant/switchTenant',
    params,
    headers,
  })
}
